package com.knife.blog.web.action;

import com.knife.blog.domain.BlogConfig;
import com.knife.blog.domain.BlogInfo;
import com.knife.blog.logic.BlogConfigService;
import com.knife.blog.logic.TemplateGenerater;
import com.knife.blog.logic.impl.BlogConfigServiceImpl;
import com.knife.util.CommUtil;
import com.knife.web.Globals;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;
import com.knife.web.tools.IActiveUser;
import com.knife.web.tools.IPageList;

public class BlogFirstPageAction extends BaseCrudAction {
	
	private BlogConfigService blogConfigService = BlogConfigServiceImpl.getInstance();
	
    @Override
	public Object doBefore(WebForm form,Module module){
		blog = userService.getUserBlog(this.getCurrentUser(form).getUserName());
		return null;
	}
	
	public Page doEdit(WebForm form, Module module){
		IActiveUser user = this.getCurrentUser(form);
		BlogInfo myblog = userService.getUserBlog(user.getUserName());
		BlogConfig config = blogConfigService.getBlogConfig(myblog.getConfigsn());
		String navigate = config.getNavigate();
		String[] navigates = navigate.split(",");
		String[] navigateFile = new String[navigates.length];
		for(int i=0;i<navigates.length;i++){
			navigateFile[i] = Globals.APP_BASE_DIR + 
			"/WEB-INF/templates/blog/template/common/navigate-" + navigates[i] + ".html";
		}
		form.addResult("config", config);
		form.addResult("navigate", navigates);
		return module.findPage("edit");
		
	}
	
	public Page doSave(WebForm form, Module module){
		BlogConfig config = (BlogConfig)form2Obj(form);
		boolean ret = blogConfigService.save(config);
		if(ret){
			String navigate = config.getNavigate();
			String[] navigates = navigate.split(",");
			String[] navigateFile = new String[navigates.length];
			for(int i=0;i<navigates.length;i++){
				navigateFile[i] = Globals.APP_BASE_DIR + 
					"/WEB-INF/templates/blog/template/common/navigate-" + navigates[i] + ".html";
			}
			String path = Globals.APP_BASE_DIR + 
				"/WEB-INF/templates/blog/userTemplate/" + blog.getDomain() + "/template.html";
			TemplateGenerater.generateTemplate(navigateFile, path);
			form.addResult("msg", "博客设置成功，将在几分钟后生效！");
		}else{
			form.addResult("msg", "博客设置失败！");
		}
		return module.findPage("edit");
	}

	@Override
	public IPageList doQuery(WebForm form, int currentPage, int pageSize) {
		// TODO 自动生成方法存根
		return null;
	}

	@Override
	public Object form2Obj(WebForm form) {
		String cid = CommUtil.null2String(form.get("cid"));
		BlogConfig obj = blogConfigService.getBlogConfig(cid);
		if (obj == null)
			obj = new BlogConfig();
		form.toPo(obj);
		return obj;
	}

}
